package com.itheima.filters;

import com.itheima.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


// @WebFilter(urlPatterns = {"/*"})
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 准备工作：获取 请求参数 和响应数据的参数
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //     1，先获取 url getRequestURL
        String requestURI = request.getRequestURI();
        //     2,判断url中 是否包含 login
        if (requestURI.contains("login")) {
            //  有token   放行
            filterChain.doFilter(servletRequest, servletResponse);
        }

        //     读取token
        String token = request.getHeader("Token");

        //     token没有内容
        if (token == null) {
            //     设置响应状态吗 为 401
            response.setStatus(401);
            return;
        }
        //     校验token

        try {
            JwtUtils.parseJWT(token);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            // throw new RuntimeException(e);
            response.setStatus(401);
            return;
        }


    }
}
